package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.dto.subject.SubjectData;
import com.atguigu.eduservice.entity.dto.subject.TreeOneSubject;
import com.atguigu.eduservice.entity.dto.subject.TreeTwoSubject;
import com.atguigu.eduservice.listener.SubjectListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-09-23
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<TreeOneSubject> getTreeEntity() {
        // 一级分类
        LambdaQueryWrapper<EduSubject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduSubject::getParentId, "0");
        List<EduSubject> entityList = this.list(wrapper);

        // 二级分类
        LambdaQueryWrapper<EduSubject> twoWrapper = new LambdaQueryWrapper<>();
        twoWrapper.ne(EduSubject::getParentId, "0");
        List<EduSubject> twoEntityList = this.list(twoWrapper);
        // 封装一级分类
        List<TreeOneSubject> oneSubjects = new ArrayList<>();
        for (EduSubject eduSubject : entityList) {
            TreeOneSubject treeOneSubject = new TreeOneSubject();
            treeOneSubject.setId(eduSubject.getId());
            treeOneSubject.setTitle(eduSubject.getTitle());

            // 封装二级分类
            List<TreeTwoSubject> twoSubjects = new ArrayList<>();
            for (EduSubject subject : twoEntityList) {
                if(subject.getParentId().equals(eduSubject.getId())){
                    TreeTwoSubject treeTwoSubject = new TreeTwoSubject();
                    treeTwoSubject.setId(subject.getId());
                    treeTwoSubject.setTitle(subject.getTitle());
                    twoSubjects.add(treeTwoSubject);
                }
            }
            treeOneSubject.setChildren(twoSubjects);
            oneSubjects.add(treeOneSubject);
        }
        return oneSubjects;
    }

}
